package cn.demoncat.util.lang.entity;

import java.io.Serializable;

/**
 * 字符串添加器
 *
 * 1、模仿StringBuilder，进行便捷性更改，因为包保护问题，大部分功能进行阉割，主要进行append操作
 * 2、StringBuilder添加null为'null' > StringAppender添加null为''
 *
 * @author 延晓磊
 * @since 2021年04月17日
 */
public class StringAppender extends AbstractStringAppender implements Serializable, CharSequence{

    private static final long serialVersionUID = 1;

    /**
     * Constructs a string builder with no characters in it and an initial capacity of 16 characters.
     *
     * appender.toString == ''
     */
    public StringAppender() {
        super(16);
    }

    /**
     * Constructs a string builder initialized to the contents of the specified string.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringAppender(String str) {
        super(16 + (str == null ? 0 : str.length()));
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters as the specified CharSequence
     *
     * @param   seq   the sequence to copy.
     */
    public StringAppender(CharSequence seq) {
        super(16 + (seq == null ? 0 : seq.length()));
        append(seq);
    }

    public StringAppender append(Object obj) {
        if(obj == null){
            return this;
        }else{
            return append(obj.toString());
        }
    }

    @Override
    public StringAppender append(String str) {
        if(str != null && str.length() > 0){
            super.append(str);
        }
        return this;
    }

    @Override
    public StringAppender delete(int start, int end) {
        super.delete(start, end);
        return this;
    }

    @Override
    public StringAppender deleteCharAt(int index) {
        super.deleteCharAt(index);
        return this;
    }

    @Override
    public StringAppender reverse() {
        super.reverse();
        return this;
    }

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }

    public StringBuilder toStringBuilder() {
        return new StringBuilder(this);
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return super.substring(start, end);
    }

    /**
     * 拼接多个
     *
     * @param strs
     * @return
     *
     * @author 延晓磊
     * @since 2021年04月17日
     */
    public StringAppender join(String ... strs){
        if(strs != null && strs.length > 0){
            for (String str : strs){
                append(str);
            }
        }
        return this;
    }

    /**
     * 拼接多个
     *
     * @param objs
     * @return
     *
     * @author 延晓磊
     * @since 2021年04月17日
     */
    public StringAppender join(Object ... objs){
        if(objs != null && objs.length > 0){
            for (Object obj : objs){
                append(obj);
            }
        }
        return this;
    }

}
